<template>
  <div class="vue-uploader">
    <p style="color: black;padding-left:15px;font-size: 17px">{{name}}
      <span v-show="required=='true'" style="" class="required">*</span>

      <span v-show="placeholder">{{placeholder}}</span>

    </p>
    <div class="file-list">
      <section v-for="(file, index) in files" class="file-item draggable-item">
        <img :src="file.src" alt="" ondragstart="return false;" @click="show(index)">
        <!--<p class="file-name">{{file.name}}</p>-->
        <span class="file-remove" @click="remove(index)">+</span>
      </section>
      <section @click="add($event)" v-if="status == 'ready'" class="file-item needsclick">
        <div class="add needsclick">
          <span class="needsclick">+</span>
        </div>
      </section>
    </div>

    <!--    <section v-if="files.length != 0" class="upload-func">
          <div class="progress-bar">
            <section v-if="uploading" :width="(percent * 100) + '%'">{{(percent * 100) + '%'}}</section>
          </div>
          <div class="operation-box">
            <button v-if="status == 'ready'" @click="submit">上传</button>
            <button v-if="status == 'finished'" @click="finished">完成</button>
          </div>
        </section>-->

    <input type="file" @change="fileChanged" ref="file">

    <div>
      <img style="display:none" class="previewer-demo-img" v-for="(item, index) in list" :src="item.src" width="100" @click="show(index)">
      <div v-transfer-dom>
        <previewer :list="list" ref="previewer" :options="options"></previewer>
      </div>
    </div>

  </div>
</template>

<script type="text/ecmascript-6">
/* eslint-disable*/
//http://img.ihuipao.cn/image/png/ae9cac70bd622e9acc4c21789323c5d3.png
import { Previewer, TransferDom } from "vux";

let srclist = [];
import { postImage } from "@/api/postImage.js";
export default {
  props: {
    item: {
      type: Object
    },
    defaultstate: {
      type: String,
      default: "normal"
    },
    name: {
      type: String,
      required: true
    },
    src: {
      type: String,
      required: true
    },
    required: {
      required: false
    },
    index: {
      type: Number,
      required: true
    },
    placeholder: {
      type: String
    }
  },
  data() {
    return {
      status: "ready",
      files: [],
      point: {},
      uploading: false,
      percent: 0,
      srcList: [],
      options: {
        getThumbBoundsFn(index) {
          // find thumbnail element
          let thumbnail = document.querySelectorAll(".previewer-demo-img")[
            index
          ];
          // get window scroll Y
          let pageYScroll =
            window.pageYOffset || document.documentElement.scrollTop;
          // optionally get horizontal scroll
          // get position of element relative to viewport
          let rect = thumbnail.getBoundingClientRect();
          // w = width
          return { x: rect.left, y: rect.top + pageYScroll, w: rect.width };
          // Good guide on how to get element coordinates:
          // http://javascript.info/tutorial/coordinates
        }
      }
    };
  },
  computed: {
    list: function() {
      let array = [];
      //console.log(this.srcList)
      this.srcList.forEach(function(item, index) {
        // console.log(item);
        array.push({ src: "//img.ihuipao.cn/" + item });
      });
      return array;
    }
  },
  created() {
    //console.log('-----')
    //console.log(this.item)
    

    if (!!this.item) {
      this.item.img.files.forEach((item, index) => {
        if (item.hasOwnProperty("src")) {
          item.src = item.src.replace("//img.ihuipao.cn/", "");
          item = item.src;
          this.files.push({ src: "//img.ihuipao.cn/" + item.src });
          this.srcList.push({ src: "//img.ihuipao.cn/" + item.src });
          this.$emit("fileChange", {
            files: this.srcList,
            index: this.index
          });
        } else {
          this.files.push({ src: "//img.ihuipao.cn/" + item });
          this.srcList.push({ src: "//img.ihuipao.cn/" + item });
          this.$emit("fileChange", {
            files: this.srcList,
            index: this.index
          });
        }
      });
    } else {
      return 
      var list = [];
      

      this.item.img.forEach((item, index) => {
        //  console.log(this.item.img)

        if (item.hasOwnProperty("src")) {
          //console.log(item)
          //console.log(this.item.length)
          item.src = item.src.replace("//img.ihuipao.cn/", "");
          item = item.src;
          this.files.push({ src: "//img.ihuipao.cn/" + item.src });
          this.srcList.push({ src: "//img.ihuipao.cn/" + item.src });

          

          if (item.hasOwnProperty("src")) {
            var str = item.src.replace("//img.ihuipao.cn/", "");
            item = str;
          } else {
          }
          list.push(item);

          this.$emit("fileChange", {
            files: list,
            index: this.index
          });
        } else {
          this.files.push({ src: "//img.ihuipao.cn/" + item });
          this.srcList.push({ src: "//img.ihuipao.cn/" + item });

          if (item.hasOwnProperty("src")) {
            var str = item.src.replace("//img.ihuipao.cn/", "");
            item = str;
          } else {
          }

          list.push(item);
          

          this.$emit("fileChange", {
            files: list,
            index: this.index
          });
        }
      });
    }

    //this.files.push({src:'http://stor.ihuipao.cn/image/5c6004f8d4fde460d999e7acde0390e1.jpg'})
    //this.files[0].src= 'http://img.ihuipao.cn/'+this.item.img[0]
  },
  methods: {
    show(index) {
      this.$refs.previewer.show(index);
    },
    add(e) {
      this.$refs.file.click();
    },
    submit() {
      if (this.files.length === 0) {
        //console.warn('没有上传的文件')
        return;
      }
      console.log(this.files);

      const formData = new FormData();
      this.files.forEach(item => {
        formData.append(item.name, item.file);
      });
      const xhr = new XMLHttpRequest();
      xhr.upload.addEventListener("progress", this.uploadProgress, false);
      xhr.open("POST", this.src, true);
      this.uploading = true;
      xhr.send(formData);
      xhr.onload = () => {
        this.uploading = false;
        if (xhr.status === 200 || xhr.status === 304) {
          this.status = "finished";
          //console.log('upload success!')
        } else {
          //console.log(`error：error code ${xhr.status}`)
        }
      };
    },
    finished() {
      this.files = [];
      this.status = "ready";
    },
    remove(index) {
      this.files.splice(index, 1);
      this.srcList.splice(index, 1);
      //srclist.splice(index, 1)
    },
    fileChanged() {
      const list = this.$refs.file.files;
      for (let i = 0; i < list.length; i++) {
        if (!this.isContain(list[i])) {
          const item = {
            name: list[i].name,
            size: list[i].size,
            file: list[i]
          };
          this.html5Reader(list[i], item);
          this.files.push(item);
        }
      }

      this.$refs.file.value = "";
      //把文件数据传递给父组件
    },
    // 将图片文件转成BASE64格式
    html5Reader(file, item) {
      const reader = new FileReader();
      reader.onload = e => {
        //this.srcList.push(e.target.result)
        //this.$set(item, 'src', e.target.result)

        this.$vux.loading.show({
          text: "图片上传中"
        });
        postImage(this.src, {
          key: "file",
          file: e.target.result
        }).then(response => {
          this.$vux.loading.hide();
          if (response.data.code == "200") {
            srclist.push(response.data.data.path);
            this.srcList.push(response.data.data.path);
            this.$set(
              item,
              "src",
              "//img.ihuipao.cn/" + response.data.data.path
            );
            // console.log(srclist)
            // console.log(this.srcList)
            // console.log(this.srcList[0])
            var imgList = {
              files: this.srcList,
              index: this.index
            };

            //console.warn(imgList);
            var list = [];
            imgList.files.forEach(function(item, index) {
              // console.warn(item)
              if (item.hasOwnProperty("src")) {
                var str = item.src.replace("//img.ihuipao.cn/", "");
                item = str;
              } else {
              }
              list.push(item);
            });

            this.$emit("fileChange", {
              files: list,
              index: this.index
            });
          } else {
            this.$vux.toast.show({
              type: "warn",
              text: response.data.msg
            });
          }
        });
      };
      reader.readAsDataURL(file);
    },
    isContain(file) {
      for (let i = 0; i < this.files.length; i++) {
        if (
          this.files[i].name === file.name &&
          this.files[i].size === file.size
        ) {
          this.$vux.toast.show({
            type: "warn",
            text: "不能上传重复的文件"
          });
          return true;
        }
      }
      return false;
    },
    uploadProgress(evt) {
      const component = this;
      if (evt.lengthComputable) {
        const percentComplete = Math.round(evt.loaded * 100 / evt.total);
        component.percent = percentComplete / 100;
      } else {
        //console.warn('upload progress unable to compute')
      }
    }
  },
  directives: {
    TransferDom
  },
  components: {
    Previewer
  }
};
</script>
<style lang="less" rel="stylesheet/less">
.vue-uploader {
  border: 1px solid #e5e5e5;
  padding-top: 10px;
}

.vue-uploader .file-list {
  padding: 10px 15px;
}

.vue-uploader .file-list:after {
  content: "";
  display: block;
  clear: both;
  visibility: hidden;
  line-height: 0;
  height: 0;
  font-size: 0;
}

.vue-uploader .file-list .file-item {
  float: left;
  position: relative;
  width: 100px;
  text-align: center;
}

.vue-uploader .file-list .file-item img {
  width: 80px;
  height: 80px;
  border: 1px solid #ececec;
}

.vue-uploader .file-list .file-item .file-remove {
  position: absolute;
  right: 12px;
  display: block;
  top: 4px;
  width: 20px;
  height: 20px;
  color: white;
  cursor: pointer;
  line-height: 15px;
  border-radius: 100%;
  -webkit-transform: rotate(45deg);
  transform: rotate(45deg);
  background: rgba(0, 0, 0, 0.5);
  font-size: 20px;
}

.vue-uploader .file-list .file-item:hover .file-remove {
  display: inline;
}

.vue-uploader .file-list .file-item .file-name {
  margin: 0;
  height: 40px;
  word-break: break-all;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.vue-uploader .add {
  width: 80px;
  height: 80px;
  margin-left: 10px;
  float: left;
  text-align: center;
  line-height: 80px;
  border: 1px dashed #ececec;
  font-size: 30px;
  cursor: pointer;
}

.vue-uploader .upload-func {
  display: flex;
  padding: 10px;
  margin: 0px;
  background: #f8f8f8;
  border-top: 1px solid #ececec;
}

.vue-uploader .upload-func .progress-bar {
  flex-grow: 1;
}

.vue-uploader .upload-func .progress-bar section {
  margin-top: 5px;
  background: #00b4aa;
  border-radius: 3px;
  text-align: center;
  color: #fff;
  font-size: 12px;
  transition: all 0.5s ease;
}

.vue-uploader .upload-func .operation-box {
  flex-grow: 0;
  padding-left: 10px;
}

.vue-uploader .upload-func .operation-box button {
  padding: 4px 12px;
  color: #fff;
  background: #007acc;
  border: none;
  border-radius: 2px;
  cursor: pointer;
}

.vue-uploader > input[type="file"] {
  display: none;
}

#form .button-wrapper {
  margin-top: 30px;
  margin-bottom: 30px;
}



.vue-uploader .required {
  display: inline-block;
  color: #f43530;
}
</style>

 